package lex.mxbeans.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;

import org.lex.swing.ActionBuilder;

import lex.mxbeans.MXBeans;
import lex.mxbeans.utils.MXBeanInfo;

public class MXBeansBrowser extends JInternalFrame
{
	private MXBeansList list = null;
	private JPanel pane = null;

	public MXBeansBrowser()
	{
		this.setClosable( false );
		this.setResizable( true );
		this.setMaximizable( true );
		this.setIconifiable( false );
		this.setTitle( "All MXBeans" );
		// ============================
		list = new MXBeansList();
		list.setComponentPopupMenu( new Popup() );
		list.addMouseListener( new MouseAdapter(){
			@Override
			public void mouseClicked( MouseEvent e )
			{
				if( e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1 )
				{
					viewSelected();
				}
			}
		} );
		// ============================
		pane = new JPanel( new BorderLayout() );
		pane.add( new JScrollPane( list ), BorderLayout.CENTER );
		this.setContentPane( pane );
	}

	private void viewSelected()
	{
		MXBeanInfo[] beans = list.getSelectedMXBeans();
		if( 0 == beans.length )
			return;
		for( MXBeanInfo bean : beans )
			MXBeans.getApplication().getContentPane().showMXBean( bean );
	}

	private class Popup extends JPopupMenu
	{
		private ActionBuilder viewAction = null;

		public Popup()
		{
			// initialize
			viewAction = new ActionBuilder( "View" );
			viewAction.setActionListener( new ActionListener(){
				@Override
				public void actionPerformed( ActionEvent e )
				{
					viewSelected();
				}
			} );
			// add to popup
			this.add( viewAction );
		}

		@Override
		public void show( Component invoker, int x, int y )
		{
			if( 0 == list.getSelectedIndices().length )
				viewAction.setEnabled( false );
			else
				viewAction.setEnabled( true );
			super.show( invoker, x, y );
		}
	}
}
